package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {
    @Resource
    private ApArticleMapper apArticleMapper;

    @Override
    public ResponseResult collectArticle(Integer userId, Long articleId, Boolean isCollect) {
        if(userId== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(articleId== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApCollection collection = getOne(new LambdaQueryWrapper<ApCollection>()
                .eq(ApCollection::getEntryId, userId)
                .eq(ApCollection::getArticleId, articleId)
                        .eq(ApCollection::getType, 0)
                );
        ApArticle article=apArticleMapper.selectById(articleId);
        if(article== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(isCollect){
            if(collection== null){
                // 未收藏，执行收藏操作
                ApCollection apCollection = new ApCollection();
                apCollection.setEntryId(userId);
                apCollection.setArticleId(articleId);
                apCollection.setType((short) 0); // 0表示文章类型
                apCollection.setCollectionTime(new Date());
                apCollection.setPublishedTime(new Date());
                boolean save = save(apCollection);


                if(save){
                    // 增加文章收藏数
                    article.setCollection(article.getCollection() + 1);
                    apArticleMapper.updateById(article);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }
            }
        }
        else{
            if (collection != null) {
                // 已收藏，执行取消收藏操作
                boolean b = removeById(collection.getId());
                if(b){
                    // 减少文章收藏数
                    if (article.getCollection() > 0) {
                        article.setCollection(article.getCollection() - 1);
                        apArticleMapper.updateById(article);
                    }
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
                }
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult isArticleCollected(Integer userId, Long articleId) {
        if(userId== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(articleId== null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer count= baseMapper.selectCount(new LambdaQueryWrapper<ApCollection>()
                .eq(ApCollection::getEntryId, userId)
                .eq(ApCollection::getArticleId, articleId)
                .eq(ApCollection::getType, 0)
        );
        Map<String,Boolean> map = new HashMap<>();
        map.put("isCollected",count > 0);
        return ResponseResult.okResult(map);
    }

    // 在 ApCollectionServiceImpl.java 中添加以下方法实现

    @Override
    public ResponseResult getUserCollections(Integer userId, Integer page, Integer size) {
        // 参数校验
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户ID不能为空");
        }

        if (page == null || page <= 0) {
            page = 1;
        }

        if (size == null || size <= 0 || size > 50) {
            size = 10;
        }

        // 分页查询用户收藏的文章ID
        Page<ApCollection> collectionPage = new Page<>(page, size);
        LambdaQueryWrapper<ApCollection> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApCollection::getEntryId, userId)
                .eq(ApCollection::getType, 0) // 0表示文章类型
                .orderByDesc(ApCollection::getCollectionTime);

        Page<ApCollection> collectionResult = page(collectionPage, queryWrapper);

        // 提取文章ID列表
        List<Long> articleIds = collectionResult.getRecords().stream()
                .map(ApCollection::getArticleId)
                .collect(Collectors.toList());

        // 根据文章ID查询文章详情
        List<ApArticle> articles = new ArrayList<>();
        LambdaQueryWrapper<ApArticle> articleQueryWrapper = new LambdaQueryWrapper<>();
        articleQueryWrapper.in(ApArticle::getId, articleIds);
        articles = apArticleMapper.selectList(articleQueryWrapper);
        if(articles.isEmpty()){
            return ResponseResult.okResult(new Page<>());
        }


        // 构造返回结果
        Page<ApArticle> articlePage = new Page<>(page, size, collectionResult.getTotal());
        articlePage.setRecords(articles);

        return ResponseResult.okResult(articlePage);
    }


}
